package com.thinkingstar.iads.projectcenter.controller;

import com.thinkingstar.iads.common.filter.GlobalsFilter;
import com.thinkingstar.iads.common.filter.UserLoginFilter;
import com.thinkingstar.iads.common.jsonUtils.AjaxResult;
import com.thinkingstar.iads.common.utils.*;
import com.thinkingstar.iads.datacenter.entity.*;
import com.thinkingstar.iads.datacenter.entity.common.dao.CommonDao;
import com.thinkingstar.iads.datacenter.entity.dao.DaoDcFormField;
import com.thinkingstar.iads.datacenter.entity.dao.DaoDcProjectDesignCell;
import com.thinkingstar.iads.datacenter.entity.dao.DaoDcProjectDesignPhase;
import com.thinkingstar.iads.datacenter.entity.dao.DaoDcProjectMention;
import com.thinkingstar.iads.datacenter.serviceImpl.DataDesignManagerServiceImpl;
import com.thinkingstar.iads.projectcenter.entity.*;
import com.thinkingstar.iads.projectcenter.entity.dao.DaoPcEquipmentEquip;
import com.thinkingstar.iads.projectcenter.entity.dao.DaoPcProjectData;
import com.thinkingstar.iads.projectcenter.entity.dao.DaoPcProjectEquipmentEquipInfo;
import com.thinkingstar.iads.projectcenter.entity.dao.DaoPcProjectFile;
import com.thinkingstar.iads.projectcenter.serviceImpl.ProjectDesignManagerServiceImpl;
import com.thinkingstar.iads.projectcenter.serviceImpl.ProjectSjpsServiceImpl;
import com.thinkingstar.iads.projectcenter.serviceImpl.ProjectTczlServiceImpl;
import com.thinkingstar.iads.projectcenter.util.SgtFileEnum;
import com.zhuozhengsoft.pageoffice.*;
import com.zhuozhengsoft.pageoffice.wordwriter.DataRegion;
import com.zhuozhengsoft.pageoffice.wordwriter.DataRegionInsertType;
import com.zhuozhengsoft.pageoffice.wordwriter.DataTag;
import com.zhuozhengsoft.pageoffice.wordwriter.WordDocument;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.List;

/**
 * 提出资料相关
 * @author z
 *
 */
@IocBean
@At("/projectCenter/tczl")
@Filters({ @By(type = GlobalsFilter.class) , @By(type = UserLoginFilter.class)})
public class ProjectTczlController {

    private static Log log = Logs.get();

    @Inject
    DataDesignManagerServiceImpl dataDesignManagerServiceImpl;

    @Inject ProjectTczlServiceImpl projectTczlService;

    @Inject
    private DaoDcProjectMention daoDcProjectMention;

    @Inject
    private DaoDcProjectDesignCell daoDcProjectDesignCell;

    @Inject
    private DaoPcEquipmentEquip daoPcEquipmentEquip;

    @Inject
    private DaoPcProjectEquipmentEquipInfo daoPcProjectEquipmentEquipInfo;

    @Inject
    CommonDao commonDao;

    @Inject
    DaoPcProjectFile daoPcProjectFile;

    @Inject
    DaoPcProjectData daoPcProjectData;

    @Inject
    ProjectSjpsServiceImpl projectSjpsService;

    @Inject
    private DaoDcProjectDesignPhase daoDcProjectDesignPhase;

    @Inject
    private DaoDcFormField daoDcFormField;

    @Inject
    private ProjectDesignManagerServiceImpl projectDesignManagerServiceImpl;

    /**
     * 点击提出资料 进入页面
     * */
    @At("/index/?")
    @Ok("beetl:/projectRoot/pcCenter/tczl/index.html")
    public NutMap index(String project_id) {
        NutMap nutMap = new NutMap();
        nutMap.put("project_id", project_id);
        List<NutMap> list = projectTczlService.getDcTczlFileList(nutMap);
        //获取这个阶段所有提入资料 里的非结构化文件
        List<NutMap> listNew = projectSjpsService.getMentionFjghByPhaseAndContentId(nutMap);
        PcProjectInfo projectInfo = daoPcProjectData.fetch(project_id);
        /** 动用所 施工图阶段添加两个文件 20190129*/
        List<NutMap> sgList = new ArrayList<>();
        DcProjectDesignPhase dcProjectDesignPhase = daoDcProjectDesignPhase.fetch(projectInfo.getProject_design_phase_id());
        if (dcProjectDesignPhase.getProject_design_phase_name().contains("施工图")&& projectInfo.getProject_design_content_name().equals("动车运用所")){
            NutMap map1 = new NutMap();
            map1.put("id","jcksbtz");
            map1.put("file_name","检查库设备提资");
            NutMap map2 = new NutMap();
            map2.put("id","lxxlksbtz");
            map2.put("file_name","临修镟轮库设备提资");
            sgList.add(map1);
            sgList.add(map2);
        }
        nutMap.put("listSgt",sgList);
       /* List<NutMap> trzl = new ArrayList<NutMap>();
        if (projectInfo.getProject_design_content_name().equals("动车运用所")){
            for (int i=0;i<listNew.size();i++){
                String fileName = (String)listNew.get(i).get("mention_information_name");
                if (fileName.equals("车站表")){
                    listNew.get(i).put("mention_information_name","02车站表");
                    trzl.add(listNew.get(i));
                } else if (fileName.equals("上阶段审查意见")){
                    listNew.get(i).put("mention_information_name","01上阶段审查意见");
                    trzl.add(listNew.get(i));
                }
            }
            nutMap.put("listNew",trzl);
        } else {
            nutMap.put("listNew",listNew);
        }*/
        nutMap.put("listNew",new ArrayList<NutMap>());
        nutMap.put("list",list);
        return nutMap;
    }

    /**
     * 动用所 施工图 添加的两个文件 详情页面
     * */
    @At("/sgtFileDetail/?")
    @Ok("beetl:/projectRoot/pcCenter/tczl/sgtfiledetail.html")
    public NutMap sgtFileDetail(String id){
        NutMap nutMap = new NutMap();
        List<NutMap> list = new ArrayList<>();
        List<SgtFileEnum> files = new ArrayList<>();
        String type = id;
        if (id.equals("jcksbtz")){//检查库设备提资
            files = SgtFileEnum.getJcksbtz();
        } else {//临修镟轮库设备提资
            files = SgtFileEnum.getLxxlksbtz();
        }
        for (int i=0;i<files.size();i++){
            SgtFileEnum file = files.get(i);
            NutMap map = new NutMap();
            map.put("id",file.getId());
            map.put("name",file.getName());
            map.put("full_name",file.getFull_name());
            map.put("type",file.getType());
            list.add(map);
        }
        nutMap.put("type",type);
        nutMap.put("list",list);
        return nutMap;
    }

    /** 一键下载*/
    @At("/downAllSgtFile/?")
    @Ok("raw:stream")
    public void downAllSgtFile(String id,HttpServletRequest req,HttpServletResponse rep){
        List<SgtFileEnum> files = SgtFileEnum.getJcksbtz();
        List<SgtFileEnum> files1 = SgtFileEnum.getJcksbtz_06();
        List<SgtFileEnum> files2 = SgtFileEnum.getLxxlksbtz();
        List<SgtFileEnum> files3 = SgtFileEnum.getLxxlksbtz_01();
        List<SgtFileEnum> files4 = SgtFileEnum.getLxxlksbtz_06();
        String filePath = "";
        List<File> fileList = new ArrayList<>();
        if (id.equals("jcksbtz")){
            filePath = InitSystemProperties.getSystemPath()+File.separator+InitSystemProperties.getSystemFilePath()+File.separator+InitSystemProperties.getBusinessPath()+File.separator+"sgtsbtz"+File.separator+"jck"+File.separator;
            for (int i=0;i<files.size();i++){
                if(files.get(i).getId().equals("6")){
                    for (int j=0;j<files1.size();j++){
                       File file = new File(filePath+files.get(i).getFull_name()+File.separator+files1.get(j).getFull_name());
                       fileList.add(file);
                    }
                } else {
                    File file = new File(filePath+File.separator+files.get(i).getFull_name());
                    fileList.add(file);
               }
            }
            DownloadFileUtil.batchDownLoadFile(fileList, "检查库设备提资.zip", req, rep);
        } else {
            filePath = InitSystemProperties.getSystemPath()+File.separator+InitSystemProperties.getSystemFilePath()+File.separator+InitSystemProperties.getBusinessPath()+File.separator+"sgtsbtz"+File.separator+"lxxlk"+File.separator;
            for (int i=0;i<files2.size();i++){
                if(files2.get(i).getId().equals("14")){
                    for (int j=0;j<files3.size();j++){
                        File file = new File(filePath+files2.get(i).getFull_name()+File.separator+files3.get(j).getFull_name());
                        fileList.add(file);
                    }
                } else if (files2.get(i).getId().equals("19")){
                    for (int j=0;j<files4.size();j++){
                        File file = new File(filePath+files2.get(i).getFull_name()+File.separator+files4.get(j).getFull_name());
                        fileList.add(file);
                    }
                } else {
                    File file = new File(filePath+files2.get(i).getFull_name());
                    fileList.add(file);
                }
            }
            DownloadFileUtil.batchDownLoadFile(fileList, "临修镟轮库设备提资.zip", req, rep);
        }

    }


    /**
     * 动用所 施工图 添加的两个文件 详情页面
     * */
    @At("/downSgtFile/?/?")
    @Ok("raw:stream")
    public void downSgtFile(String file_id,String project_id,HttpServletRequest req,HttpServletResponse rep){
        String filePath = "";
        List<SgtFileEnum> jcksbtz = SgtFileEnum.getJcksbtz();
        List<SgtFileEnum> lxxlksbtz = SgtFileEnum.getLxxlksbtz();
        List<File> fileList = new ArrayList<>();
        for (int i=0;i<jcksbtz.size();i++){
            filePath = InitSystemProperties.getSystemPath()+File.separator+InitSystemProperties.getSystemFilePath()+File.separator+InitSystemProperties.getBusinessPath()+File.separator+"sgtsbtz"+File.separator+"jck"+File.separator;
            if (file_id.equals(jcksbtz.get(i).getId())){
                if (jcksbtz.get(i).getType().equals("1")){//单个文件下载
                    DownloadFileUtil.fileStream(filePath+File.separator+jcksbtz.get(i).getFull_name(), req, rep);
                } else {//打包下载
                    if (jcksbtz.get(i).getId().equals("6")){
                        List<SgtFileEnum> jcksbtz_fj06 = SgtFileEnum.getJcksbtz_06();
                        for (int j=0;j<jcksbtz_fj06.size();j++){
                            File file = new File(filePath+jcksbtz.get(i).getFull_name()+File.separator+jcksbtz_fj06.get(j).getFull_name());
                            fileList.add(file);
                        }
                        DownloadFileUtil.batchDownLoadFile(fileList, jcksbtz.get(i).getName()+".zip", req, rep);
                    }
                }
            }
        }
        for (int i=0;i<lxxlksbtz.size();i++){
            if (file_id.equals(lxxlksbtz.get(i).getId())){
                filePath = InitSystemProperties.getSystemPath()+File.separator+InitSystemProperties.getSystemFilePath()+File.separator+InitSystemProperties.getBusinessPath()+File.separator+"sgtsbtz"+File.separator+"lxxlk"+File.separator;
                if (lxxlksbtz.get(i).getType().equals("1")){//单个文件下载
                    DownloadFileUtil.fileStream(filePath+lxxlksbtz.get(i).getFull_name(), req, rep);
                } else {//打包下载
                    if (lxxlksbtz.get(i).getId().equals("14")){
                        List<SgtFileEnum> lxxlk_fj01 = SgtFileEnum.getLxxlksbtz_01();
                        for (int j=0;j<lxxlk_fj01.size();j++){
                            File file = new File(filePath+lxxlksbtz.get(i).getFull_name()+File.separator+lxxlk_fj01.get(j).getFull_name());
                            fileList.add(file);
                        }
                        DownloadFileUtil.batchDownLoadFile(fileList, lxxlksbtz.get(i).getName()+".zip", req, rep);
                    } else if(lxxlksbtz.get(i).getId().equals("19")){
                        List<SgtFileEnum> lxxlk_fj06 = SgtFileEnum.getLxxlksbtz_06();
                        for (int j=0;j<lxxlk_fj06.size();j++){
                            File file = new File(filePath+lxxlksbtz.get(i).getFull_name()+File.separator+lxxlk_fj06.get(j).getFull_name());
                            fileList.add(file);
                        }
                        DownloadFileUtil.batchDownLoadFile(fileList, lxxlksbtz.get(i).getName()+".zip", req, rep);
                    }

                }

            }
        }
    }


   /* *//**
     *查询 提出资料 文件列表
     * *//*
    @At("/queryFileList")
    @Ok("json:full")
    public Object queryFileList(@Param("..") NutMap param, HttpServletRequest request, HttpServletResponse response){
        //查询数据中心 设计评审资料库
        return projectTczlService.findSjpsTemplateList(param);
    }*/

    /**
     * 点击去合成 进入页面
     * */
    @At("/toMerge/?/?")
    @Ok("beetl:/projectRoot/pcCenter/tczl/merge.html")
    public NutMap toMerge(String project_id,String wjid, HttpServletRequest req , HttpServletResponse rep)  throws IOException {
        NutMap nutMap = new NutMap();
        nutMap.put("project_id", project_id);
        nutMap.put("wjid",wjid);

        //根据id查询 合成规则
        DcProjectPutFord dcProjectPutFord = projectTczlService.getDcProjectPutFordById(wjid);
        //根据模板文件filecode获取项目中心 是否已经配置 文件合成规则
        PcTczlFile tczlFile = projectTczlService.getPcTczlFile(project_id,dcProjectPutFord.getPutford_code());

        //合成规则str
        String compound_rule = "";
        if (null!=tczlFile) {
            //说明项目该模板有保存过合成规则
            compound_rule = tczlFile.getSorting();
        } else {//未保存过，取数据中心保存的合成规则
            compound_rule = dcProjectPutFord.getCompound_rule();
        }

        List<PcMergeData> mergeData = new ArrayList<>();

        //提入资料
        String mention_data_id = dcProjectPutFord.getMention_data();
        List<DcProjectMentionInformation> mentionList = projectSjpsService.getMentionDataListByIds(mention_data_id);
        for(int i=0;i<mentionList.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(mentionList.get(i).getId());
            data.setFileName(mentionList.get(i).getMention_information_name());
            data.setFileNum(mentionList.get(i).getMention_information_code());
            if (mentionList.get(i).getMention_information_type()) {
                data.setType("trzl_jgh");//提入资料 结构化
            } else {
                data.setType("trzl_fjgh");//非提入资料 结构化
            }

            if (compound_rule.contains(mentionList.get(i).getMention_information_name())) {
                data.setCheck(true);
            }
            mergeData.add(data);
            System.out.println("create file start--------------------------------"+mentionList.get(i).getMention_information_name()+"------------");
            exportMentionExcelData(project_id,mentionList.get(i).getId(),req,rep);
        }

        //根据提入资料id获取提入资料
        String mention_data = projectSjpsService.getMentionDataByIds(mention_data_id);
        nutMap.put("mention_data",mention_data);

        //设计单元
        String design_cell_id = dcProjectPutFord.getDesign_cell_data();
        List<DcProjectDesignCell> designcell = projectSjpsService.getDesignCellListByIds(design_cell_id);
        for(int i=0;i<designcell.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(designcell.get(i).getId());
            data.setFileName(designcell.get(i).getDesign_cell_table_name());
            data.setFileNum(designcell.get(i).getDesign_cell_table_code());
            data.setType("sjdy");//设计单元
            if (compound_rule.contains(designcell.get(i).getDesign_cell_table_name())) {
                data.setCheck(true);
            }
            mergeData.add(data);
            System.out.println("create file start--------------------------------"+designcell.get(i).getDesign_cell_table_code()+"------------");
            exportDesignCellExcelData(project_id,designcell.get(i).getId(),req,rep);
        }

        //根据设计单元id获取设计单元
        String design_cell_data = projectSjpsService.getDesignCellByIds(design_cell_id);
        nutMap.put("design_cell_data",design_cell_data);

        //根据模板id获取模板列表
        String template_id = dcProjectPutFord.getCompound_template();
        List<DcCompoundTemplate> template = projectTczlService.getTemplateListByIds(template_id);
        for(int i=0;i<template.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(template.get(i).getId());
            data.setFileName(template.get(i).getTemplate_name());
            data.setFileNum(template.get(i).getTemplate_code());
            data.setType("mb");//模板
            if (compound_rule.contains(template.get(i).getTemplate_name())) {
                data.setCheck(true);
            }
            mergeData.add(data);
        }
        PcProjectInfo projectInfo = daoPcProjectData.fetch(project_id);
        if (projectInfo.getProject_design_content_name().equals("物资总库")) {//过滤条件
            Map map = sxWj(project_id,mergeData,compound_rule);
            nutMap.put("list",map.get("list"));
            nutMap.put("compound_rule",map.get("compound_rule"));
        } else {
            nutMap.put("list",mergeData);
            nutMap.put("compound_rule",compound_rule);
        }
        return nutMap;
    }

    //物资总库按 项目主要技术标准 表 数据做 判断
    public Map<String,Object> sxWj(String project_id,List<PcMergeData> list,String compound_rule) {
        //根据项目id查询 项目主要技术标准表
        List<DcProjectMentionInformation> dcProjectMentionInformations = daoDcProjectMention.query(Cnd.where("mention_information_name","like","%项目专用信息%"));
        String xmzyjsbz_name = "";
        if (null!=dcProjectMentionInformations && dcProjectMentionInformations.size()>0) {
            xmzyjsbz_name = "dc_mention_"+dcProjectMentionInformations.get(0).getMention_information_code();
        }
        //项目主要技术标准表 数据
        List <NutMap> result = commonDao.findOrderDataListByTableName(project_id,xmzyjsbz_name);
        NutMap data = null;
        if (null!=result && result.size()>0) {
            data = result.get(0);
        }
        //停放线数量
        String tfx = "";
        if(null!=data && data.get("zhgqsfphgdcz").toString().equals("on") && data.get("zhgqsfszgcck").toString().equals("on")) {
            if (data.get("zhgqgdczdzc").toString().equals("2轨道车2平车2携吊平车")) {
               //2条停放线
                tfx = "2条停放线";
            } else {
                tfx = "2条停放线";
            }
        } else if (null!=data && data.get("zhgqsfphgdcz").toString().equals("off") && data.get("zhgqsfszgcck").toString().equals("on")){
            tfx = "1条停放线";
        }
        boolean sfszgcck = false;//是否设置工程车库
        boolean sfszgdcz = false;//是否设置轨道车组
        boolean sfszjcj = false;//是否设置架车机
        boolean sfdytx = false;//是否第1条线
        if (null!=data && data.get("zhgqsfszgcck").toString().equals("on")) {//工程车库
            sfszgcck = true;
        }
        if(null!=data && data.get("sfszjcj").toString().equals("on")) {//架车机
            sfszjcj = true;
        }
        if(null!=data && data.get("zhgqsfphgdcz").toString().equals("on")) {//轨道车组
            sfszgdcz = true;
        }
        if(null!=data && data.get("sfdytx").toString().equals("on")) {//是否第1条线
            sfdytx = true;
        }
        Iterator<PcMergeData> it = list.iterator();
        while(it.hasNext()){
            PcMergeData pcMergeData = it.next();
            //对给排水专业 暖通专业  通信专业要求 筛选
            if(sfszgcck) {//有工程车库
                if (pcMergeData.getFileName().equals("对给排水专业要求（无综合工区工程车库）") || pcMergeData.getFileName().equals("对暖通专业要求（无综合工区工程车库）") ||
                        pcMergeData.getFileName().equals("对通信专业要求（无综合工区工程车库）") || pcMergeData.getFileName().equals("对电力要求模板03（不设工程车库）")) {
                    it.remove();
                    compound_rule = compound_rule.replace("对给排水专业要求（无综合工区工程车库）","");
                    compound_rule = compound_rule.replace("对暖通专业要求（无综合工区工程车库）","");
                    compound_rule = compound_rule.replace("对通信专业要求（无综合工区工程车库）","");
                    compound_rule = compound_rule.replace("对电力要求模板03（不设工程车库）","");
                }
            } else {
                if (pcMergeData.getFileName().equals("对给排水专业要求（有综合工区工程车库）")|| pcMergeData.getFileName().equals("对暖通专业要求（有综合工区工程车库）") ||
                        pcMergeData.getFileName().equals("对通信专业要求（有综合工区工程车库）") || pcMergeData.getFileName().equals("对电力要求模板03（设工程车库）") ||
                        pcMergeData.getFileName().equals("综合工区工程车库用电")) {
                    it.remove();
                    compound_rule = compound_rule.replace("对给排水专业要求（有综合工区工程车库）","");
                    compound_rule = compound_rule.replace("对暖通专业要求（有综合工区工程车库）","");
                    compound_rule = compound_rule.replace("对通信专业要求（有综合工区工程车库）","");
                    compound_rule = compound_rule.replace("对电力要求模板03（设工程车库）","");
                    compound_rule = compound_rule.replace("综合工区工程车库用电","");
                }
            }
            //对战场专业要求 筛选
            if (tfx.equals("1条停放线") && !sfszjcj){
                if (pcMergeData.getFileName().equals("对站场专业要求（不设架车机，2条停放线）")|| pcMergeData.getFileName().equals("对站场专业要求（设架车机，1条停放线）") ||
                        pcMergeData.getFileName().equals("对站场专业要求（设架车机，2条停放线）")) {
                    it.remove();
                    compound_rule = compound_rule.replace("对站场专业要求（不设架车机，2条停放线）","");
                    compound_rule = compound_rule.replace("对站场专业要求（设架车机，1条停放线）","");
                    compound_rule = compound_rule.replace("对站场专业要求（设架车机，2条停放线）","");
                }
            } else if (tfx.equals("2条停放线") && !sfszjcj) {
                if (pcMergeData.getFileName().equals("对站场专业要求（不设架车机，1条停放线）")|| pcMergeData.getFileName().equals("对站场专业要求（设架车机，1条停放线）") ||
                        pcMergeData.getFileName().equals("对站场专业要求（设架车机，2条停放线）")) {
                    it.remove();
                    compound_rule = compound_rule.replace("对站场专业要求（不设架车机，1条停放线）","");
                    compound_rule = compound_rule.replace("对站场专业要求（设架车机，1条停放线）","");
                    compound_rule = compound_rule.replace("对站场专业要求（设架车机，2条停放线）","");
                }
            } else if (tfx.equals("1条停放线") && sfszjcj) {
                if (pcMergeData.getFileName().equals("对站场专业要求（不设架车机，1条停放线）")|| pcMergeData.getFileName().equals("对站场专业要求（不设架车机，2条停放线）") ||
                        pcMergeData.getFileName().equals("对站场专业要求（设架车机，2条停放线）")) {
                    it.remove();
                    compound_rule = compound_rule.replace("对站场专业要求（不设架车机，1条停放线）","");
                    compound_rule = compound_rule.replace("对站场专业要求（不设架车机，2条停放线）","");
                    compound_rule = compound_rule.replace("对站场专业要求（设架车机，2条停放线）","");
                }
            } else if (tfx.equals("2条停放线") && sfszjcj) {
                if (pcMergeData.getFileName().equals("对站场专业要求（不设架车机，1条停放线）")|| pcMergeData.getFileName().equals("对站场专业要求（不设架车机，2条停放线）") ||
                        pcMergeData.getFileName().equals("对站场专业要求（设架车机，1条停放线）")) {
                    it.remove();
                    compound_rule = compound_rule.replace("对站场专业要求（不设架车机，1条停放线）","");
                    compound_rule = compound_rule.replace("对站场专业要求（不设架车机，2条停放线）","");
                    compound_rule = compound_rule.replace("对站场专业要求（设架车机，1条停放线）","");
                }
            }
            //总体设计原则 筛选
            if (sfdytx && !sfszgdcz){
                if (pcMergeData.getFileName().equals("总体设计原则模板（第1条线，设轨道车库）")|| pcMergeData.getFileName().equals("总体设计原则模板（非第1条线，不设轨道车库）") ||
                        pcMergeData.getFileName().equals("总体设计原则模板（非第1条线，设轨道车库）")) {
                    it.remove();
                    compound_rule = compound_rule.replace("总体设计原则模板（第1条线，设轨道车库）","");
                    compound_rule = compound_rule.replace("总体设计原则模板（非第1条线，不设轨道车库）","");
                    compound_rule = compound_rule.replace("总体设计原则模板（非第1条线，设轨道车库）","");
                }
            } else if (sfdytx && sfszgdcz) {
                if (pcMergeData.getFileName().equals("总体设计原则模板（第1条线，不设轨道车库）")|| pcMergeData.getFileName().equals("总体设计原则模板（非第1条线，不设轨道车库）") ||
                        pcMergeData.getFileName().equals("总体设计原则模板（非第1条线，设轨道车库）")) {
                    it.remove();
                    compound_rule = compound_rule.replace("总体设计原则模板（第1条线，不设轨道车库）","");
                    compound_rule = compound_rule.replace("总体设计原则模板（非第1条线，不设轨道车库）","");
                    compound_rule = compound_rule.replace("总体设计原则模板（非第1条线，设轨道车库）","");
                }
            } else if (!sfdytx && !sfszgdcz) {
                if (pcMergeData.getFileName().equals("总体设计原则模板（第1条线，不设轨道车库）")|| pcMergeData.getFileName().equals("总体设计原则模板（第1条线，设轨道车库）") ||
                        pcMergeData.getFileName().equals("总体设计原则模板（非第1条线，设轨道车库）")) {
                    it.remove();
                    compound_rule = compound_rule.replace("总体设计原则模板（第1条线，不设轨道车库）","");
                    compound_rule = compound_rule.replace("总体设计原则模板（第1条线，设轨道车库）","");
                    compound_rule = compound_rule.replace("总体设计原则模板（非第1条线，设轨道车库）","");
                }
            } else if (!sfdytx && sfszgdcz) {
                if (pcMergeData.getFileName().equals("总体设计原则模板（第1条线，不设轨道车库）")|| pcMergeData.getFileName().equals("总体设计原则模板（第1条线，设轨道车库）") ||
                        pcMergeData.getFileName().equals("总体设计原则模板（非第1条线，不设轨道车库）")) {
                    it.remove();
                    compound_rule = compound_rule.replace("总体设计原则模板（第1条线，不设轨道车库）","");
                    compound_rule = compound_rule.replace("总体设计原则模板（第1条线，设轨道车库）","");
                    compound_rule = compound_rule.replace("总体设计原则模板（非第1条线，不设轨道车库）","");
                }
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("list",list);
        map.put("compound_rule",compound_rule);
        return map;
    }


    //导出提入资料excel和word数据
    public void exportMentionExcelData(String project_id,String mention_data_id , HttpServletRequest req , HttpServletResponse rep) throws IOException {
        DcProjectMentionInformation dcProjectMentionInformation = daoDcProjectMention.fetch(mention_data_id);
        String table_name = new StringBuffer("dc_mention_").append(dcProjectMentionInformation.getMention_information_code()).toString();
        List<NutMap> dataList = commonDao.findDataListByTableName(project_id,table_name);
        List <NutMap> field_list = daoDcFormField.queryHradListByTable(table_name);
        String file_name = dcProjectMentionInformation.getMention_information_name()+".xls";
        String word_name = dcProjectMentionInformation.getMention_information_name()+".docx";
        System.out.println("create exportMentionExcelData start------------"+table_name+"--------------------"+file_name+"----------"+word_name+"------------");
        List<Map> countList = daoDcFormField.countField(field_list,table_name,project_id);
        if (dcProjectMentionInformation.getMention_information_type()){//结构化数据表单
            File docx_file = ExcelPoiUtil.createWordAddCount(word_name,project_id,"提入资料_jgh",field_list,dataList,countList);
            File excel_file = ExcelPoiUtil.createExcelAddCount(file_name, project_id,"提入资料_jgh",field_list,dataList,countList);
        }
    }

    //导出设计单元excel和word数据
    public void exportDesignCellExcelData(String project_id,String design_cell_id , HttpServletRequest req , HttpServletResponse rep) throws IOException {
        DcProjectDesignCell dcProjectDesignCell = daoDcProjectDesignCell.fetch(design_cell_id);
        String table_name = new StringBuffer("dc_designcell_").append(dcProjectDesignCell.getDesign_cell_table_code()).toString();
        List<NutMap> dataList = commonDao.findDataListByTableName(project_id,table_name);
        List <NutMap> field_list = daoDcFormField.queryHradListByTable(table_name);
        String file_name = dcProjectDesignCell.getDesign_cell_table_name()+".xls";
        String word_name = dcProjectDesignCell.getDesign_cell_table_name()+".docx";
        System.out.println("create exportDesignCellExcelData start---------"+table_name+"------------------------"+file_name+"----------"+word_name+"------------");
        List<Map> countList = daoDcFormField.countField(field_list,table_name,project_id);
        File docx_file = ExcelPoiUtil.createWordAddCount(word_name,project_id,"设计单元",field_list,dataList,countList);
        File excel_file = ExcelPoiUtil.createExcelAddCount(file_name,project_id,"设计单元",field_list,dataList,countList);
    }

    //导出设备配备excel和word数据
    public void exportSbpbExcelData(String project_id , HttpServletRequest req , HttpServletResponse rep) throws IOException {
        //设备配备表名 pc_equipment_equip
        PcProjectEquipmentEquip sbb1 = daoPcEquipmentEquip.findEquipmentEquipByProjectIdAndName(project_id,"综合工区设备配备");
        PcProjectEquipmentEquip sbb2 = daoPcEquipmentEquip.findEquipmentEquipByProjectIdAndName(project_id,"综合维修中心设备配备");
        PcProjectEquipmentEquip sbb3 = daoPcEquipmentEquip.findEquipmentEquipByProjectIdAndName(project_id,"物资总库设备配备");
        //设备配备表数据 pc_equipment_equip_info
        List<PcProjectEquipmentEquipInfo> eqInfos1 = daoPcProjectEquipmentEquipInfo.findEquipmentEquipInfoByEquipId(sbb1.getId());
        List<PcProjectEquipmentEquipInfo> eqInfos2 = daoPcProjectEquipmentEquipInfo.findEquipmentEquipInfoByEquipId(sbb2.getId());
        List<PcProjectEquipmentEquipInfo> eqInfos3 = daoPcProjectEquipmentEquipInfo.findEquipmentEquipInfoByEquipId(sbb3.getId());

        List<NutMap> dataList1 = new ArrayList<>();
        for (int i=0;i<eqInfos1.size();i++) {
            NutMap nutMap = new NutMap();
            nutMap.put("serial_number",i+1);
            nutMap.put("equipment_name",eqInfos1.get(i).getEquipment_name());
            nutMap.put("equipment_num",eqInfos1.get(i).getEquipment_num());
            nutMap.put("equipment_price",eqInfos1.get(i).getEquipment_price());
            dataList1.add(nutMap);
        }
        List<NutMap> dataList2 = new ArrayList<>();
        for (int i=0;i<eqInfos2.size();i++) {
            NutMap nutMap = new NutMap();
            nutMap.put("serial_number",i+1);
            nutMap.put("equipment_name",eqInfos2.get(i).getEquipment_name());
            nutMap.put("equipment_num",eqInfos2.get(i).getEquipment_num());
            nutMap.put("equipment_price",eqInfos2.get(i).getEquipment_price());
            dataList2.add(nutMap);
        }
        List<NutMap> dataList3 = new ArrayList<>();
        for (int i=0;i<eqInfos3.size();i++) {
            NutMap nutMap = new NutMap();
            nutMap.put("serial_number",i+1);
            nutMap.put("equipment_name",eqInfos3.get(i).getEquipment_name());
            nutMap.put("equipment_num",eqInfos3.get(i).getEquipment_num());
            nutMap.put("equipment_price",eqInfos3.get(i).getEquipment_price());
            dataList3.add(nutMap);
        }

        List<NutMap> fieldList = new ArrayList<>();
        NutMap map1 = new NutMap();
        map1.put("field_type","varchar");
        map1.put("field_comment","设备名称");
        map1.put("field_name","equipment_name");

        NutMap map2 = new NutMap();
        map2.put("field_type","varchar");
        map2.put("field_comment","设备数量");
        map2.put("field_name","equipment_num");

        NutMap map3 = new NutMap();
        map3.put("field_type","varchar");
        map3.put("field_comment","设备单价");
        map3.put("field_name","equipment_price");
        fieldList.add(map1);
        fieldList.add(map2);
        fieldList.add(map3);

        File docx_file1 = ExcelPoiUtil.createWord("综合工区设备配备.docx",project_id,"设备配备",fieldList,dataList1);
        File excel_file1 = ExcelPoiUtil.createExcel("综合工区设备配备.xls",project_id,"设备配备",fieldList,dataList1);

        File docx_file2 = ExcelPoiUtil.createWord("综合维修中心设备配备.docx",project_id,"设备配备",fieldList,dataList1);
        File excel_file2 = ExcelPoiUtil.createExcel("综合维修中心设备配备.xls",project_id,"设备配备",fieldList,dataList1);

        File docx_file3 = ExcelPoiUtil.createWord("物资总库设备配备.docx",project_id,"设备配备",fieldList,dataList1);
        File excel_file3 = ExcelPoiUtil.createExcel("物资总库设备配备.xls",project_id,"设备配备",fieldList,dataList1);
    }

    /**
     * 保存合成规则
     * */
    @At("/saveSorting/?/?")
    @Ok("json:full")
    public Object saveSorting(String project_id,String wjid,String sorting) {
        //根据id查询 合成规则
        DcProjectPutFord dcProjectPutFord = projectTczlService.getDcProjectPutFordById(wjid);
        projectTczlService.insertOrUpdatePcTczlFile(project_id,sorting,dcProjectPutFord.getPutford_code());
        return AjaxResult.success();
    }

    /**
     * 手动保存合成规则  2019/01/23
     *
     * */
    public void saveSortingNew(String project_id,String wjid,HttpServletResponse resp,HttpServletRequest req) throws Exception{
        NutMap nutMap = new NutMap();
        nutMap.put("project_id", project_id);
        nutMap.put("wjid",wjid);

        //根据id查询 合成规则
        DcProjectPutFord dcProjectPutFord = projectTczlService.getDcProjectPutFordById(wjid);
        //根据模板文件filecode获取项目中心 是否已经配置 文件合成规则
        PcTczlFile tczlFile = projectTczlService.getPcTczlFile(project_id,dcProjectPutFord.getPutford_code());

        //合成规则str
        String compound_rule = "";
        if (null!=tczlFile) {
            //说明项目该模板有保存过合成规则
            compound_rule = tczlFile.getSorting();
        } else {//未保存过，取数据中心保存的合成规则
            compound_rule = dcProjectPutFord.getCompound_rule();
        }

        List<PcMergeData> mergeData = new ArrayList<>();

        //提入资料
        String mention_data_id = dcProjectPutFord.getMention_data();
        List<DcProjectMentionInformation> mentionList = projectSjpsService.getMentionDataListByIds(mention_data_id);
        for(int i=0;i<mentionList.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(mentionList.get(i).getId());
            data.setFileName(mentionList.get(i).getMention_information_name());
            data.setFileNum(mentionList.get(i).getMention_information_code());
            if (mentionList.get(i).getMention_information_type()) {
                data.setType("trzl_jgh");//提入资料 结构化
            } else {
                data.setType("trzl_fjgh");//非提入资料 结构化
            }

            if (compound_rule.contains(mentionList.get(i).getMention_information_name())) {
                data.setCheck(true);
            }
            mergeData.add(data);
            System.out.println("create file start--------------------------------"+mentionList.get(i).getMention_information_name()+"------------");
            exportMentionExcelData(project_id,mentionList.get(i).getId(),req,resp);
        }

        //根据提入资料id获取提入资料
        String mention_data = projectSjpsService.getMentionDataByIds(mention_data_id);
        nutMap.put("mention_data",mention_data);

        //设计单元
        String design_cell_id = dcProjectPutFord.getDesign_cell_data();
        List<DcProjectDesignCell> designcell = projectSjpsService.getDesignCellListByIds(design_cell_id);
        for(int i=0;i<designcell.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(designcell.get(i).getId());
            data.setFileName(designcell.get(i).getDesign_cell_table_name());
            data.setFileNum(designcell.get(i).getDesign_cell_table_code());
            data.setType("sjdy");//设计单元
            if (compound_rule.contains(designcell.get(i).getDesign_cell_table_name())) {
                data.setCheck(true);
            }
            mergeData.add(data);
            System.out.println("create file start--------------------------------"+designcell.get(i).getDesign_cell_table_code()+"------------");
            exportDesignCellExcelData(project_id,designcell.get(i).getId(),req,resp);
        }

        //根据设计单元id获取设计单元
        String design_cell_data = projectSjpsService.getDesignCellByIds(design_cell_id);
        nutMap.put("design_cell_data",design_cell_data);

        //根据模板id获取模板列表
        String template_id = dcProjectPutFord.getCompound_template();
        List<DcCompoundTemplate> template = projectTczlService.getTemplateListByIds(template_id);
        for(int i=0;i<template.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(template.get(i).getId());
            data.setFileName(template.get(i).getTemplate_name());
            data.setFileNum(template.get(i).getTemplate_code());
            data.setType("mb");//模板
            if (compound_rule.contains(template.get(i).getTemplate_name())) {
                data.setCheck(true);
            }
            mergeData.add(data);
        }
        PcProjectInfo projectInfo = daoPcProjectData.fetch(project_id);
        String sorting = "";
        if (projectInfo.getProject_design_content_name().equals("物资总库")) {//过滤条件
            Map map = sxWj(project_id,mergeData,compound_rule);
            nutMap.put("list",map.get("list"));
            nutMap.put("compound_rule",map.get("compound_rule"));
            sorting = map.get("compound_rule").toString();
        } else {
            nutMap.put("list",mergeData);
            nutMap.put("compound_rule",compound_rule);
            sorting = compound_rule;
        }
        projectTczlService.insertOrUpdatePcTczlFile(project_id,sorting,dcProjectPutFord.getPutford_code());
    }

    /**
     *    实现在线预览功能直接网页显示不使用pageoffice预览
     *
     * @param file_id
     * @param request
     * @return
     * @throws FileNotFoundException
     */
    @At("/previewDataFile/?")
    @Ok("raw")
    public String previewFile(String file_id , HttpServletRequest request) throws FileNotFoundException{
        String serverIp= InitSystemProperties.get("preview.server.ip");
        String serverPort = InitSystemProperties.get("preview.server.port");
        String previewServer ="http://"+serverIp+":"+serverPort;

        PcProjectFile pcProjectFile = daoPcProjectFile.fetch(file_id);
        if(pcProjectFile != null){
            String relative_path = pcProjectFile.getRelativePaths();
            String open_url = previewServer+"/"+FileCommonUtil.pathToURI(relative_path);
            //String open_url = "previewServer"+"/"+FileCommonUtil.pathToURI(relative_path);
            String url = previewServer+"/onlinePreview?url="+open_url;
            // String testurl = "http://192.168.31.100:8082/preview"+"/onlinePreview?url="+"http://192.168.31.100:8082/preview"+"/"+FileCommonUtil.pathToURI(relative_path);
            return url;
        }
        return "";
    }

    /**
     * 点击设计评审 合成
     * */
    @At("/mergeWord/?/?/?")
    @Ok("beetl:/projectRoot/pcCenter/pageOffice/merge_word.html")
    public NutMap mergeWord(String project_id,String wjid,String hcType,HttpServletRequest request,HttpServletResponse response)  throws IOException ,Exception{
        saveSortingNew(project_id,wjid,response,request);
        NutMap nutMap = new NutMap();
        nutMap.put("project_id", project_id);
        //根据id查询 合成规则
        DcProjectPutFord dcProjectPutFord = projectTczlService.getDcProjectPutFordById(wjid);

        //hcType =0 合成，hcType=1 重新合成
        //点合成的时候 查询有没有保存 过，如果保存过那么直接取
        //点重新合成，那么就不管原来的文件，直接走合成流程
        if (hcType.equals("0")) {
            //判断是否已经保存过，保存过，那么直接取 保存过的合成文档，不需要重新合成
            String filePath = POIFileUtil.getFilePathByType("提出资料",project_id)+dcProjectPutFord.getPutford_code()+".docx";
            File file = new File(filePath);
            if (file.exists()){
                //文件存在  说明合成过
                PageOfficeCtrl poCtrl=new PageOfficeCtrl(request);
                poCtrl.setServerPage(request.getContextPath()+"/poserver.zz");//设置服务页面
                poCtrl.addCustomToolButton("保存","Save",1);//添加自定义保存按钮
                poCtrl.setSaveFilePage(request.getContextPath()+"/projectCenter/tczl/savefile/"+project_id+"/"+wjid);//设置处理文件保存的请求方法
                poCtrl.setJsFunction_AfterDocumentSaved("AfterDocumentSaved");
                poCtrl.setTheme(ThemeType.Office2010);
                poCtrl.webOpen(request.getContextPath()+"/projectCenter/tczl/downFile/"+"tczl__"+wjid+"/"+project_id,OpenModeType.docNormalEdit,"杨震");
                poCtrl.setTagId("PageOfficeCtrl1"); //此行必须
                poCtrl.webCreateNew("张三", DocumentVersion.Word2007);
                nutMap.put("pageoffice",poCtrl.getHtmlCode("PageOfficeCtrl1"));
                return nutMap;
            }
        }


        //根据模板文件filecode获取项目中心 是否已经配置 文件合成规则
        PcTczlFile tczlFile = projectTczlService.getPcTczlFile(project_id,dcProjectPutFord.getPutford_code());

        //合成规则str
        String compound_rule = "";
        if (null!=tczlFile) {
            //说明项目该模板有保存过合成规则
            compound_rule = tczlFile.getSorting();
        } else {//未保存过，取数据中心保存的合成规则
            compound_rule = dcProjectPutFord.getCompound_rule();
        }

        List<PcMergeData> mergeData = new ArrayList<>();
        List<PcMergeData> mergeDataNew = new ArrayList<>();

        //提入资料
        String mention_data_id = dcProjectPutFord.getMention_data();
        List<DcProjectMentionInformation> mentionList = projectSjpsService.getMentionDataListByIds(mention_data_id);
        for(int i=0;i<mentionList.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(mentionList.get(i).getId());
            data.setFileName(mentionList.get(i).getMention_information_name());
            data.setFileNum(mentionList.get(i).getMention_information_code());
            if (mentionList.get(i).getMention_information_type()) {
                data.setType("trzl_jgh");//提入资料_结构化
            } else {
                data.setType("trzl_fjgh");//提入资料_非结构化
            }
            //if (compound_rule.contains(mentionList.get(i).getMention_information_name())) {
            mergeData.add(data);
            //}
        }

        //设计单元
        String design_cell_id = dcProjectPutFord.getDesign_cell_data();
        List<DcProjectDesignCell> designcell = projectSjpsService.getDesignCellListByIds(design_cell_id);
        for(int i=0;i<designcell.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(designcell.get(i).getId());
            data.setFileName(designcell.get(i).getDesign_cell_table_name());
            data.setFileNum(designcell.get(i).getDesign_cell_table_code());
            data.setType("sjdy");//设计单元
            //if (compound_rule.contains(designcell.get(i).getDesign_cell_table_name())) {
            mergeData.add(data);
            //}
        }

        //根据项目id查询 项目所有常量
       // List<PcProjectConstantData> constantData = projectSjpsService.getConstantData(project_id);

        //根据模板id获取模板列表
        String template_id = dcProjectPutFord.getCompound_template();
        List<DcCompoundTemplate> template = projectTczlService.getTemplateListByIds(template_id);
        for(int i=0;i<template.size();i++) {
            PcMergeData data = new PcMergeData();
            data.setId(template.get(i).getId());
            data.setFileName(template.get(i).getTemplate_name());
            data.setFileNum(template.get(i).getTemplate_code());
            data.setType("mb");//模板
            //if (compound_rule.contains(template.get(i).getTemplate_name())) {
            mergeData.add(data);
            //}
        }


        String[] str = compound_rule.split("、");
        for (int j=0;j<str.length;j++) {
            for (int i=0;i<mergeData.size();i++) {
                if (str[j].equals(mergeData.get(i).getFileName())) {
                    mergeDataNew.add(mergeData.get(i));
                }
            }
        }
        boolean isSjxz = false;
        PcProjectInfo  pc = daoPcProjectData.fetch(project_id);
        if (pc.getProject_design_content_name().equals("物资总库") && compound_rule.contains("设计细则")) {
            exportSbpbExcelData(project_id,request,response);
            isSjxz = true;
        }
        boolean isSbgs = false;
        if (pc.getProject_design_content_name().equals("物资总库") && compound_rule.contains("设备概算")){
           // exportSbgsExcelData(project_id,request,response);
            isSbgs = true;
        }
        WordDocument docx = word(mergeDataNew,project_id,isSjxz,isSbgs,request,response);

        PageOfficeCtrl poCtrl=new PageOfficeCtrl(request);
        poCtrl.setServerPage(request.getContextPath()+"/poserver.zz");//设置服务页面
        poCtrl.addCustomToolButton("保存","Save",1);//添加自定义保存按钮
        poCtrl.setSaveFilePage(request.getContextPath()+"/projectCenter/tczl/savefile/"+project_id+"/"+wjid);//设置处理文件保存的请求方法
        poCtrl.setJsFunction_AfterDocumentSaved("AfterDocumentSaved");
        poCtrl.setTheme(ThemeType.Office2010);
        poCtrl.setWriter(docx);
        poCtrl.setTagId("PageOfficeCtrl1"); //此行必须
        poCtrl.webCreateNew("张三", DocumentVersion.Word2007);
        nutMap.put("pageoffice",poCtrl.getHtmlCode("PageOfficeCtrl1"));
        return nutMap;
    }

    public WordDocument word(List<PcMergeData> data ,String project_id,boolean isSjxz,boolean isSbgs, HttpServletRequest request,HttpServletResponse response){
        boolean ok = true;
        String str = "";
        String msg = "";
        Map<String,String> map = new HashMap<>();
        String sysPath = InitSystemProperties.getSystemPath()+File.separator+InitSystemProperties.getSystemFilePath()+File.separator+InitSystemProperties.getBusinessPath()+File.separator;
        Map<String,String> params = new HashMap<>();
        List<PcMergeData> dataNew = new ArrayList<>();
        for (int i=0;i<data.size();i++) {
            dataNew.add(data.get(i));
        }

        for (int i=0;i<data.size();i++) {
            String filePath = "";
            File file = null;
            if (data.get(i).getType().equals("trzl_jgh")) {//提入资料
                filePath = "trzl_jgh__"+data.get(i).getId();
                file = new File(POIFileUtil.getFilePathByType("提入资料_jgh",project_id)+data.get(i).getFileName()+".docx");
                if(!file.exists()){
                    msg += data.get(i).getFileName()+" 该文件不存在，请确认上传成功\n ";
                    ok = false;
                } else {
                    map.put(data.get(i).getFileName(),request.getContextPath()+"/projectCenter/tczl/downFile/"+filePath+"/"+project_id);
                }
            } else if (data.get(i).getType().equals("trzl_fjgh")){
                DcProjectMentionInformation dcProjectMentionInformation = daoDcProjectMention.fetch(data.get(i).getId());
                String table_name = new StringBuffer("dc_mention_").append(dcProjectMentionInformation.getMention_information_code()).toString();
                List<NutMap> dataList = commonDao.findDataListByTableName(project_id,table_name);
                List <NutMap> field_list = daoDcFormField.queryHradListByTable(table_name);

                for (int n=0;n<field_list.size();n++) {
                    for (int m=0;m<dataList.size();m++) {
                        String value = dataList.get(m).getString(field_list.get(n).getString("field_name"));
                        //将非结构化字段值去 pc_project_file中查询，如果有就说明是文件，如果没有说明是普通字段
                        PcProjectFile pcFile = daoPcProjectFile.fetch(value);
                        if ( null != pcFile && pcFile.getId().equals(value)) {
                            filePath = "trzl_fjgh__"+pcFile.getId();
                            String paths = InitSystemProperties.getSystemPath()+File.separator+InitSystemProperties.getSystemFilePath()+File.separator+InitSystemProperties.getBusinessPath()+File.separator+pcFile.getRelativePaths();
                            file = new File(paths);
                            PcMergeData pc = new PcMergeData();
                            pc.setType("trzl_fjgh");
                            pc.setFileName(pcFile.getName());
                            pc.setId(pcFile.getId());
                            pc.setFileNum(field_list.get(n).getString("field_name"));

                            if (pcFile.getFileExt().equals("docx")||pcFile.getFileExt().equals("doc")) {
                                dataNew.add(pc);
                                if(!file.exists()){
                                    msg += pcFile.getName()+" 该文件不存在，请确认上传成功\n ";
                                    ok = false;
                                } else {
                                   /* String ext = filePath.substring(filePath.lastIndexOf(".") + 1);
                                    String name = filePath.substring(0,filePath.lastIndexOf("."));*/
                                    map.put(pcFile.getName(),request.getContextPath()+"/projectCenter/tczl/downFile/"+filePath+"/"+project_id);
                                   // map.put(pcFile.getName().substring(0,pcFile.getName().lastIndexOf(".")),"/iads/projectCenter/sjps/downFile/"+filePath+"/"+project_id);
                                }
                            } else if (pcFile.getFileExt().equals("jpg")||pcFile.getFileExt().equals("png")) {
                                dataNew.add(pc);
                                //String name = filePath.split(".")[0];
                                //String ext = filePath.split(".")[1];
                                /*String ext = filePath.substring(filePath.lastIndexOf(".") + 1);
                                String name = filePath.substring(0,filePath.lastIndexOf("."));*/
                                if(!file.exists()){
                                    msg += pcFile.getName()+" 该文件不存在，请确认上传成功! ";
                                    ok = false;
                                } else {
                                    //map.put(pcFile.getName().substring(0,pcFile.getName().lastIndexOf(".")),"/iads/projectCenter/sjps/downFile/"+filePath+"/"+project_id);
                                    map.put(pcFile.getName(),request.getContextPath()+"/projectCenter/tczl/downFile/"+filePath+"/"+project_id);
                                }
                            }
                        }
                    }
                }
				/*filePath =
				file = new File()*/
            } else if (data.get(i).getType().equals("sjdy")) {//设计单元
                filePath = "sjdy__"+data.get(i).getId();
                file = new File(POIFileUtil.getFilePathByType("设计单元",project_id)+data.get(i).getFileName()+".docx");
                if(!file.exists()){
                    msg += data.get(i).getFileName()+" 该文件不存在，请确认上传成功\n ";
                    ok = false;
                } else {
                    map.put(data.get(i).getFileName(),request.getContextPath()+"/projectCenter/tczl/downFile/"+filePath+"/"+project_id);
                }
            } else {//模板
                List<DcCompoundTemplate> ls = projectTczlService.getTemplateListByIds(data.get(i).getId());
                if (ls.size()>0) {
                    //查询模板
                    List<DcTemplateVariable> variable = projectTczlService.getTemplateVariable(ls.get(0).getId());
                    //模板里塞值
                    params.putAll(projectTczlService.getVariableValues(variable,project_id));
                    filePath = "mb__"+ls.get(0).getId();
                    file = new File(sysPath+ls.get(0).getTemplate_file_path());
                    if(!file.exists()){
                        msg += data.get(i).getFileName()+" 该模板文件不存在，请确认上传成功\n ";
                        ok = false;
                    } else {
                        map.put(data.get(i).getFileName(),request.getContextPath()+"/projectCenter/tczl/downFile/"+filePath+"/"+project_id);
                    }
                }
            }
        }

        WordDocument docx = new WordDocument();  //这里需要按照文件名单顺序进行排序

        if(ok){
            int num = 1;
            String home = "[home]";
            DataRegion dr = null;
            for (int i = 0; i < dataNew.size(); i++) {
                if(i != 0){
                    home = "reg"+String.valueOf(num - 1);
                }
                if(StringUtils.isNotEmpty(map.get(dataNew.get(i).getFileName()))){
                    dr = docx.createDataRegion("reg"+num, DataRegionInsertType.After,home);
                    dr.setEditing(true);
                    DataRegion doc = docx.openDataRegion("PO_reg" + num);
                    if (dataNew.get(i).getFileName().endsWith("png")||dataNew.get(i).getFileName().endsWith("jpg")) {
                        doc.setValue("[image]" + map.get(dataNew.get(i).getFileName()) + "[/image]");
                    } else {
                        doc.setValue("[word]" + map.get(dataNew.get(i).getFileName()) + "[/word]");
                    }

                } else {
                    dr = docx.createDataRegion("reg"+num, DataRegionInsertType.After,home);
                    dr.setEditing(true);
                    DataRegion doc = docx.openDataRegion("PO_reg" + num);
                    doc.setValue("");
                }
                num++;
            }
        }else{
            DataRegion dr = docx.createDataRegion("msg", DataRegionInsertType.After,"[home]");
            dr.setEditing(true);
            dr.getFont().setColor(Color.RED);
            DataRegion doc = docx.openDataRegion("msg");
            doc.setValue(msg);

        }
        Set<String> keys = params.keySet();
        for(String key:keys){
            String type = key.split("__")[1];
            String k = key.split("__")[0];
            if (type.equals("DataRegion")){
                DataRegion dataRegion = docx.openDataRegion(k);
                dataRegion.setValue(params.get(k+"__"+type));
                dataRegion.getFont().setItalic(true);
                dataRegion.getShading().setBackgroundPatternColor(Color.gray);
            } else if (type.equals("DataTag")){
                DataTag dataTag = docx.openDataTag(k);
                dataTag.setValue(params.get(k+"__"+type));
                dataTag.getFont().setItalic(true);
                dataTag.getShading().setBackgroundPatternColor(Color.gray);
            } else if (type.equals("Image")){
                DataRegion dataRegion = docx.openDataRegion(k);
                String id = params.get(k+"__"+type);
                if (StringUtils.isNotEmpty(id)){
                    //根据提入资料里的图片id 获取图片路径
                    dataRegion.setValue("[image]"+request.getContextPath()+"/projectCenter/sjps/downFile/trzl_fjgh__"+id+"/"+project_id+"[/image]");
                } else {
                    dataRegion.setValue(k+"图片不存在");
                    dataRegion.getFont().setColor(Color.red);
                }
            } else if (type.equals("InputTable")){
                DataRegion dataRegion = docx.openDataRegion(k);
                String id = params.get(k+"__"+type);
                if (StringUtils.isNotEmpty(id)){
                    //根据提入资料id 获取文件
                    try {
                        exportMentionExcelData(project_id,id,request,response);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    dataRegion.setValue("[word]"+request.getContextPath()+"/projectCenter/sjps/downFile/trzl_jgh__"+id+"/"+project_id+"[/word]");
                } else {
                    dataRegion.setValue(k+"提入资料不存在");
                    dataRegion.getFont().setColor(Color.red);
                }
            } else if (type.equals("DesignTable")){
                DataRegion dataRegion = docx.openDataRegion(k);
                String id = params.get(k+"__"+type);
                if (StringUtils.isNotEmpty(id)){
                    //根据设计单元id 获取文件
                    try {
                        exportDesignCellExcelData(project_id,id,request,response);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    dataRegion.setValue("[word]"+request.getContextPath()+"/projectCenter/sjps/downFile/sjdy__"+id+"/"+project_id+"[/word]");
                } else {
                    dataRegion.setValue(k+"设计单元不存在");
                    dataRegion.getFont().setColor(Color.red);
                }
            }
        }
        DataTag dataTag = docx.openDataTag("{{项目名称}}");
        DataTag dataTag1 = docx.openDataTag("{{项目阶段}}");
        DataTag dataTag3 = docx.openDataTag("{{设计阶段}}");
        DataTag dataTag2 = docx.openDataTag("{{当前时间}}");
        PcProjectInfo  pc = daoPcProjectData.fetch(project_id);
        dataTag.setValue(pc.getProject_name());
        dataTag1.setValue(daoDcProjectDesignPhase.fetch(pc.getProject_design_phase_id()).getProject_design_phase_name());
        dataTag2.setValue(CommonDateUtil.formatDate(new Date()));
        dataTag3.setValue(daoDcProjectDesignPhase.fetch(pc.getProject_design_phase_id()).getProject_design_phase_name());

        //动车运用所 特殊
        if (pc.getProject_design_content_name().equals("动车运用所")){
            //取 设计单元 段长编组车数汇总
            NutMap nutMap = daoDcProjectDesignCell.findDcbzcsCountByDesignCellName(project_id,pc.getProject_design_phase_id(),pc.getProject_design_content_id(),"短长编组车数");
            if (null!=nutMap) {
                DataTag dataTag01 = docx.openDataTag("{{运用车数-近期-长编组汇总}}");
                DataTag dataTag02 = docx.openDataTag("{{运用车数-远期-长编组汇总}}");
                DataTag dataTag03 = docx.openDataTag("{{运用车数-近期-短编组汇总}}");
                DataTag dataTag04 = docx.openDataTag("{{运用车数-远期-短编组汇总}}");
                DataTag dataTag05 = docx.openDataTag("{{配属车数-近期-长编组汇总}}");
                DataTag dataTag06 = docx.openDataTag("{{配属车数-远期-长编组汇总}}");
                DataTag dataTag07 = docx.openDataTag("{{配属车数-近期-短编组汇总}}");
                DataTag dataTag08 = docx.openDataTag("{{配属车数-远期-短编组汇总}}");
                dataTag01.getFont().setColor(Color.red);
                dataTag02.getFont().setColor(Color.red);
                dataTag03.getFont().setColor(Color.red);
                dataTag04.getFont().setColor(Color.red);
                dataTag05.getFont().setColor(Color.red);
                dataTag06.getFont().setColor(Color.red);
                dataTag07.getFont().setColor(Color.red);
                dataTag08.getFont().setColor(Color.red);

                String cbzyycsjq = (String)nutMap.get("cbzyycsjq");
                String cbzyycsyq = (String)nutMap.get("cbzyycsyq");
                String dbzyycsjq = (String)nutMap.get("dbzyycsjq");
                String dbzyycsyq = (String)nutMap.get("dbzyycsyq");
                String cbzpscsjq = (String)nutMap.get("cbzpscsjq");
                String cbzpscsyq = (String)nutMap.get("cbzpscsyq");
                String dbzpscsjq = (String)nutMap.get("dbzpscsjq");
                String dbzpscsyq = (String)nutMap.get("dbzpscsyq");

                if (org.apache.commons.lang3.StringUtils.isNotEmpty(cbzyycsjq) && cbzyycsjq.contains(".") && cbzyycsjq.substring(cbzyycsjq.indexOf("."),cbzyycsjq.length()-1).length()>2){
                    cbzyycsjq = cbzyycsjq.substring(0,cbzyycsjq.lastIndexOf(".")+2);
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(cbzyycsyq) && cbzyycsyq.contains(".") && cbzyycsyq.substring(cbzyycsyq.indexOf("."),cbzyycsyq.length()-1).length()>2){
                    cbzyycsyq = cbzyycsyq.substring(0,cbzyycsyq.lastIndexOf(".")+2);
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(dbzyycsjq) && dbzyycsjq.contains(".") && dbzyycsjq.substring(dbzyycsjq.indexOf("."),dbzyycsjq.length()-1).length()>2){
                    dbzyycsjq = dbzyycsjq.substring(0,dbzyycsjq.lastIndexOf(".")+2);
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(dbzyycsyq) && dbzyycsyq.contains(".") && dbzyycsyq.substring(dbzyycsyq.indexOf("."),dbzyycsyq.length()-1).length()>2){
                    dbzyycsyq = dbzyycsyq.substring(0,dbzyycsyq.lastIndexOf(".")+2);
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(cbzpscsjq) && cbzpscsjq.contains(".") && cbzpscsjq.substring(cbzpscsjq.indexOf("."),cbzpscsjq.length()-1).length()>2){
                    cbzpscsjq = cbzpscsjq.substring(0,cbzpscsjq.lastIndexOf(".")+2);
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(cbzpscsyq) && cbzpscsyq.contains(".") && cbzpscsyq.substring(cbzpscsyq.indexOf("."),cbzpscsyq.length()-1).length()>2){
                    cbzpscsyq = cbzpscsyq.substring(0,cbzpscsyq.lastIndexOf(".")+2);
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(dbzpscsjq) && dbzpscsjq.contains(".") && dbzpscsjq.substring(dbzpscsjq.indexOf("."),dbzpscsjq.length()-1).length()>2){
                    dbzpscsjq = dbzpscsjq.substring(0,dbzpscsjq.lastIndexOf(".")+2);
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(dbzpscsyq) && dbzpscsyq.contains(".") && dbzpscsyq.substring(dbzpscsyq.indexOf("."),dbzpscsyq.length()-1).length()>2){
                    dbzpscsyq = dbzpscsyq.substring(0,dbzpscsyq.lastIndexOf(".")+2);
                }

                dataTag01.setValue(StringUtils.isEmpty((String)nutMap.get("cbzyycsjq"))?"":cbzyycsjq);
                dataTag02.setValue(StringUtils.isEmpty((String)nutMap.get("cbzyycsyq"))?"":cbzyycsyq);
                dataTag03.setValue(StringUtils.isEmpty((String)nutMap.get("dbzyycsjq"))?"":dbzyycsjq);
                dataTag04.setValue(StringUtils.isEmpty((String)nutMap.get("dbzyycsyq"))?"":dbzyycsyq);
                dataTag05.setValue(StringUtils.isEmpty((String)nutMap.get("cbzpscsjq"))?"":cbzpscsjq);
                dataTag06.setValue(StringUtils.isEmpty((String)nutMap.get("cbzpscsyq"))?"":cbzpscsyq);
                dataTag07.setValue(StringUtils.isEmpty((String)nutMap.get("dbzpscsjq"))?"":dbzpscsjq);
                dataTag08.setValue(StringUtils.isEmpty((String)nutMap.get("dbzpscsyq"))?"":dbzpscsyq);
            }

        } else if (pc.getProject_design_content_name().equals("物资总库")){
            if (isSjxz) {
                DataRegion dataRegion1 = docx.openDataRegion("PO_zhgqsbpbb");
                //生成设备配备文件
                dataRegion1.setValue("[word]"+request.getContextPath()+"/projectCenter/tczl/downFile/sbpb__1/"+project_id+"[/word]");
                DataRegion dataRegion2 = docx.openDataRegion("PO_wzzksbpbb");
                dataRegion2.setValue("[word]"+request.getContextPath()+"/projectCenter/tczl/downFile/sbpb__2/"+project_id+"[/word]");
                DataRegion dataRegion3 = docx.openDataRegion("PO_zhwxzxsbpbb");
                dataRegion3.setValue("[word]"+request.getContextPath()+"/projectCenter/tczl/downFile/sbpb__3/"+project_id+"[/word]");
            }
            if (isSbgs) {
                DataRegion dataRegion1 = docx.openDataRegion("PO_zhgqsbgsb");
                //生成设备概算文件
                dataRegion1.setValue("[word]"+request.getContextPath()+"/projectCenter/tczl/downFile/sbgs__1/"+project_id+"[/word]");
                DataRegion dataRegion2 = docx.openDataRegion("PO_wzzksbgsb");
                dataRegion2.setValue("[word]"+request.getContextPath()+"/projectCenter/tczl/downFile/sbgs__2/"+project_id+"[/word]");
                DataRegion dataRegion3 = docx.openDataRegion("PO_zhwxzxsbgsb");
                dataRegion3.setValue("[word]"+request.getContextPath()+"/projectCenter/tczl/downFile/sbgs__3/"+project_id+"[/word]");
            }
        }

        return docx;
    }

    /**
     * 预览下载文件
     * @param req
     */
    @GET
    @At("/downFile/?/?")
    @Ok("raw:stream")
    public void downFile(String path ,String project_id,HttpServletRequest req,HttpServletResponse resp){
        String[] str = path.split("__");
        String filePath = "";
        String sysPath = InitSystemProperties.getSystemPath()+File.separator+InitSystemProperties.getSystemFilePath()+File.separator+InitSystemProperties.getBusinessPath()+File.separator;
        if (str[0].equals("trzl_jgh")) {
            DcProjectMentionInformation pm = daoDcProjectMention.fetch(str[1]);
            filePath = POIFileUtil.getFilePathByType("提入资料_jgh",project_id)+pm.getMention_information_name()+".docx";
        } else if (str[0].equals("trzl_fjgh")){
            PcProjectFile pf = daoPcProjectFile.fetch(str[1]);
            if (null!=pf) {
                String name = pf.getName();
                filePath = InitSystemProperties.getSystemPath()+File.separator+InitSystemProperties.getSystemFilePath()+File.separator+InitSystemProperties.getBusinessPath()+File.separator+pf.getRelativePaths();
            }
        } else if (str[0].equals("sjdy")) {
            DcProjectDesignCell pd = daoDcProjectDesignCell.fetch(str[1]);
            filePath = POIFileUtil.getFilePathByType("设计单元",project_id)+pd.getDesign_cell_table_name()+".docx";
        } else if(str[0].equals("tczl")){
            DcProjectPutFord dcProjectPutFord = projectTczlService.getDcProjectPutFordById(str[1]);
            filePath = POIFileUtil.getFilePathByType("提出资料",project_id)+dcProjectPutFord.getPutford_code()+".docx";
        } else if (str[0].equals("sbpb")){
            if (str[1].equals("1")){
                filePath = POIFileUtil.getFilePathByType("设备配备",project_id)+"综合工区设备配备.docx";
            } else if (str[1].equals("2")) {
                filePath = POIFileUtil.getFilePathByType("设备配备",project_id)+"物资总库设备配备.docx";
            } else if(str[1].equals("3")) {
                filePath = POIFileUtil.getFilePathByType("设备配备",project_id)+"综合维修中心设备配备.docx";
            }
        } else if (str[0].equals("sbgs")){
            //查询 物资总库项目 设备概算 三张表
            if (str[1].equals("1")){
                filePath = POIFileUtil.getFilePathByType("设备概算",project_id)+"综合工区设备概算.docx";
            } else if (str[1].equals("2")) {
                filePath = POIFileUtil.getFilePathByType("设备概算",project_id)+"物资总库设备概算.docx";
            } else if(str[1].equals("3")) {
                filePath = POIFileUtil.getFilePathByType("设备概算",project_id)+"综合维修中心设备概算.docx";
            }
        } else {
            List<DcCompoundTemplate> ls = projectTczlService.getTemplateListByIds(str[1]);
            if (ls.size()>0) {
                filePath = sysPath + ls.get(0).getTemplate_file_path();
            }else {
                filePath = "";
            }
        }
        //File newFile=new File(filePath);
        System.out.println("download file tczl--------------------------------"+filePath);
        log.info("download file tczl--------------------------------"+filePath);
        //DownloadFileUtil.webDownloadFileUtil(newFile,newFile.getName(),req,resp);
        DownloadFileUtil.fileStream(filePath, req, resp);
        //return newFile;
    }

    /**
     * 点击预览
     * */
    @At("/preview/?/?/?")
    @Ok("beetl:/projectRoot/pcCenter/pageOffice/merge_word.html")
    public NutMap preview(String project_id,String fileId,String fileType,HttpServletRequest request) {
        System.out.println(" preview in ---------------------------"+fileType+"-----------"+fileId);
        NutMap nutMap = new NutMap();
        nutMap.put("project_id", project_id);
        WordDocument docx = new WordDocument();
        PageOfficeCtrl poCtrl=new PageOfficeCtrl(request);
        poCtrl.setServerPage(request.getContextPath()+"/poserver.zz");//设置服务页面
        poCtrl.addCustomToolButton("保存","Save",1);//添加自定义保存按钮
        poCtrl.setSaveFilePage("/save");//设置处理文件保存的请求方法
        poCtrl.setTheme(ThemeType.Office2010);
        poCtrl.setWriter(docx);
        //打开word
        String filePath = "";
        if (fileType.equals("trzl_jgh")) {
            filePath = request.getContextPath()+"/projectCenter/tczl/downFile/"+"trzl_jgh__"+fileId+"/"+project_id;
        } else if (fileType.equals("sjdy")) {
            filePath = request.getContextPath()+"/projectCenter/tczl/downFile/"+"sjdy__"+fileId+"/"+project_id;
        } else if (fileType.equals("tczl")){
            filePath = request.getContextPath()+"/projectCenter/tczl/downFile/"+"tczl__"+fileId+"/"+project_id;
        } else {
            filePath = request.getContextPath()+"/projectCenter/tczl/downFile/"+"mb__"+fileId+"/"+project_id;
        }

        System.out.println(" preview file ---------------------------"+filePath);
        poCtrl.webOpen(filePath, OpenModeType.docNormalEdit,"张三");
        poCtrl.setTagId("PageOfficeCtrl1"); //此行必须
        poCtrl.webCreateNew("张三", DocumentVersion.Word2007);
        nutMap.put("pageoffice",poCtrl.getHtmlCode("PageOfficeCtrl1"));
        return nutMap;
    }

    /**
     * pageoffice保存
     * */
    @POST
    @At("/savefile/?/?")
    @Ok("json:full")
    public AjaxResult savefile(String project_id,String wjid,HttpServletRequest req,HttpServletResponse resp) {
        NutMap nutMap = new NutMap();
        nutMap.put("project_id", project_id);
        String path = POIFileUtil.getFilePathByType("提出资料",project_id);
        DcProjectPutFord dcProjectPutFord = projectTczlService.getDcProjectPutFordById(wjid);
        FileSaver fs=new FileSaver(req,resp);
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        fs.saveToFile(path+dcProjectPutFord.getPutford_code()+".docx");
        fs.close();
        return AjaxResult.success("success");
    }

    //导出设计评审
    @At("/exportWordData/?/?")
    public void exportWordData(String wjid , String project_id, HttpServletRequest req , HttpServletResponse rep){
        //查询设计单元 表名
        String path = POIFileUtil.getFilePathByType("提出资料",project_id);
        DcProjectPutFord dcProjectPutFord = projectTczlService.getDcProjectPutFordById(wjid);
        File file = new File(path+dcProjectPutFord.getPutford_code()+".docx");
        DownloadFileUtil.downLoadFile(file, dcProjectPutFord.getPutford_name()+".docx", req, rep);
    }
}
